//index.js
const storeService = require('../../../../api/storeService.js')
const productService = require('../../../../api/productService.js')
const bannerService = require('../../../../api/bannerService.js')
const shopcartService = require('../../../../api/shopcartService.js')
const memberService = require('../../../../api/memberService.js')
const activityService = require('../../../../api/activityService.js')
const searchService = require('../../../../api/searchService.js')
const wxaUserService = require('../../../../api/wxaUserService.js')
const couponService = require('../../../../api/couponService.js')
const auth = require('../../../../utils/auth.js')
const util = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({
  data: {
    tabbar: {},
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.openSetting'),
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showTabbar: true,
    storeId: '',
    store: '',
    category: [], // 类目以及类目下商品
    tabSelected: '0',
    goodsList: [],
    banners: [],
    hasaAuthorization: true,
    adsenseList: [],
    fineQualityGoodsList: [],
    searchLabelShow: false,
    nameLikes: '',
    activityList: [],
    searchText: '',
    keywords: [],
    speechStart: false,
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false,
      coupon: false
    },
    overlayStyle: 'background: rgba(255, 255, 255, 0.9);top:88rpx;',
    phone: false,
    donateCoupons: {}
  },
  /**
   * 获取当前门店的所有分类和商品
   * @param {string} storeId 
   */
  getMenuProduct: function (storeId) {
    const that = this
    console.log(storeId)
    productService.getMenuProduct(storeId, "RETAIL").then(res => {
      let selected = this.data.tabSelected
      let tempArray = []
      if (res != '') {
        tempArray = res[selected].products
        let tempGoodsList = []
        res.forEach(item => {
          var tempData = that.productsSort(item.products)
          tempGoodsList.push(tempData)
        })
        this.setData({
          category: res,
          goodsList: tempGoodsList
        })
      } else {
        this.setData({
          category: res,
          goodsList: tempArray
        })
      }
    })
  },
  /**
   * 根据产品库存排序，库存为零的排在后面，其余位置不变
   * @param {Array} array 
   */
  productsSort: function (array) {
    let balanceArray = []
    let allArray = []
    array.forEach(ele => {
      if (ele.balance === 0) {
        balanceArray.push(ele)
      } else {
        allArray.push(ele)
      }
    });
    const tempArray = allArray.concat(balanceArray)
    return tempArray
  },
  /**
   * 获取门店精选商品
   * @param {string} storeId 
   */
  getStoreProduct: function (storeId) {
    const that = this
    productService.getStoreHotProduct(storeId).then(res => {
      console.log(res)
      let tempList = []
      if (res && res.length > 0) {
        res.forEach(item => {
          let produtlabel = []
          let promotions = []
          let specifications = ''
          if (item.labels && item.labels.length > 0) {
            item.labels.forEach(ele => {
              if (ele.type === 'GOODSLABEL') {
                produtlabel.push(ele)
              } else if (ele.type === 'PROMOTIONLABEL') {
                promotions.push(ele)
              }
            })
          }
          if (item.productProperties && item.productProperties.length > 0) {
            for (let i = 0; i < item.productProperties.length; i++) {
              const ele = item.productProperties[i];
              if (ele.propertyName === '规格') {
                specifications = ele.propertyValue
                break
              }
            }
          }
          let tempItem = {
            ...item,
            produtlabel: produtlabel,
            promotions: promotions,
            specifications: specifications
          }
          tempList.push(tempItem)
        })
        let newTempList = that.productsSort(tempList)
        that.setData({
          fineQualityGoodsList: newTempList
        })
      } else {
        that.setData({
          fineQualityGoodsList: tempList
        })
      }
    }).catch(error => {
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 获取门店首页广告位图片信息
  getAdsenseList: function (storeId) {
    bannerService.getAdsenseList(storeId).then(res => {
      // console.log(res)
      this.setData({
        adsenseList: res
      })
    }).catch(error => {
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 获取缓存的用户信息
  getMemberUserInfo: function () {
    try {
      var accessTokens = wx.getStorageSync('__access_tokens__')
      if (!app.globalData.userInfo) {
        wx.showToast({
          title: "您还未授权，请登陆授权",
          icon: 'none',
          duration: 2000
        })
      } else {
        const newDate = new Date()
        const newTemp = new Date(util.formatTime(newDate)).getTime()
        if (newTemp < accessTokens.refreshExpiresTo) {
          let user = app.globalData.userInfo
          this.setData({
            userInfo: user.wxaUser,
            hasUserInfo: true,
          })
        } else {
          // accessTokens 过期 需要重新登录
          this.setData({
            hasUserInfo: false
          })
        }
      }
    } catch (error) {
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      })
    }
  },
  getLocation: function () {
    const self = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        try {
          var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
          if (tempAllStores) {
            // Do something with return value
            let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
            app.globalData.storeInfo = tempAllStores[tempIndex];
            // 获取当前门店的所有分类和商品
            // self.getMenuProduct(tempAllStores[tempIndex].id)
            self.getStoreProduct(tempAllStores[tempIndex].id)
            self.getBannerList(tempAllStores[tempIndex].id)
            self.getIndexActivity(tempAllStores[tempIndex].id)
          } else {
            // 查询所有门店
            storeService.queryList().then(res => {
              var allStores = [];
              res.forEach(item => {
                if (item.status === 'OPEN') {
                  allStores.push(item)
                }
              });
              try {
                wx.setStorageSync('wj_allStores', allStores)
              } catch (e) {
                console.log(e)
              }
              let tempIndex = self.getNearestStore(allStores, latitude, longitude);
              return allStores[tempIndex]
            }).then(res => {
              app.globalData.storeInfo = res;
              // self.getMenuProduct(res.id)
              self.getStoreProduct(res.id)
              self.getBannerList(res.id)
              // self.getAdsenseList(res.id)
              self.getIndexActivity(res.id)
            })
          }
        } catch (e) {
          // Do something when catch error
        }
      },
      fail: function (res) {
        console.log(res)
        self.setData({
          hasaAuthorization: false
        })
        wx.hideTabBar()
      }
    })
  },
  // 设置位置权限
  openSetting: function () {
    const that = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
      },
      fail: function (res) {
        wx.showModal({
          title: '授权提示',
          content: '部分功能需要您的微信授权才能使用哦~\n错过授权页面的处理方法：删除小程序->重新搜索进入->同意授权'
        })
      }
    })
  },
  /**
   * 获取首页活动
   * 三分图、单图
   * @param {string} storeId 
   */
  getIndexActivity: function (storeId) {
    const that = this
    activityService.query(storeId).then(res => {
      console.log(res, '1')
      let tempList = []
      if (res && res.length > 0) {
        res.forEach(item => {
          let tempData = {
            ...item,
          }
          let tempProducts = []
          // 判断是单图还是三分图
          let showType = 'SINGLE' //默认单图
          for (let i = 0; i < item.imageItems.length; i++) {
            const ele = item.imageItems[i];
            if (ele.showType === 'THREE') {
              showType = 'THREE'
              break
            }
          }

          tempData.products.forEach(item => {
            let produtlabel = []
            let promotions = []
            let specifications = ''
            if (item.labels && item.labels.length > 0) {
              item.labels.forEach(ele => {
                if (ele.type === 'GOODSLABEL') {
                  produtlabel.push(ele)
                } else if (ele.type === 'PROMOTIONLABEL') {
                  promotions.push(ele)
                }
              })
            }
            if (item.productProperties && item.productProperties.length > 0) {
              for (let i = 0; i < item.productProperties.length; i++) {
                const ele = item.productProperties[i];
                if (ele.propertyName === '规格') {
                  specifications = ele.propertyValue
                  break
                }
              }
            }
            let tempItem = {
              ...item,
              produtlabel: produtlabel,
              promotions: promotions,
              specifications: specifications
            }
            tempProducts.push(tempItem)
          })
          tempData = {
            ...tempData,
            products: tempProducts,
            showType: showType
          }
          tempList.push(tempData)
        })
      }
      that.setData({
        activityList: tempList
      })
    }).catch(error => {
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  onLoad: function (options) {
    console.log("page onload")
    app.editTabbar();
    const self = this;
    this.checkAccessToken()
    // self.getMemberUserInfo()
    // 查询统配门店信息
    storeService.getDistributionStore().then(res => {
      if (res) {
        var distributionStore = res;
        try {
          wx.setStorageSync('wj_distributionStore', distributionStore)
        } catch (e) {
          console.log(e)
        }
      }
    }).catch(e => {

    })
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      this.setData({
        store: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id
      })
      // self.getMenuProduct(this.data.storeId)
      self.getStoreProduct(this.data.storeId)
      self.getBannerList(this.data.storeId)
      self.getIndexActivity(this.data.storeId)
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      self.getLocation()
    }
    if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      try {
        wx.setStorageSync('wj_sharingId', scene)
      } catch (e) {}
    }
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },
  onShow: function (options) {
    const that = this
    // this.getSearchKeyword()
    // 从授权页返回返回
    if (!this.data.hasaAuthorization) {
      wx.getSetting({
        success: (res) => {
          console.log(res)
          if (res.authSetting["scope.userLocation"]) {
            console.log("123")
            that.setData({
              hasaAuthorization: true
            })
            wx.showTabBar()
            that.getLocation()
          }
        }
      })
    }
    wx.showShareMenu({
      withShareTicket: true
    })
    if (app.globalData.storeInfo) {
      this.setData({
        store: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id
      })
      // this.getMenuProduct(this.data.storeId)
      this.getStoreProduct(this.data.storeId)
      this.getBannerList(this.data.storeId)
      this.getIndexActivity(this.data.storeId)
      if (app.globalData.userInfo) {
        this.recordVisitStore(this.data.storeId)
      }
    }
    // 从绑定手机号返回
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },

  // 搜索框点击事件,输入框聚焦
  handleFocus: function (e) {
    this.setData({
      searchLabelShow: true
    })
  },
  // 搜索框失去焦点处理
  handleBlur: function (e) {
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false
      })
    }
  },
  // 输入框输入时处理
  handleInput: function (e) {
    if (!e.detail.value) {
      this.setData({
        nameLikes: e.detail.value
      })
    }
  },
  // 输入框输入完成时处理
  handleConfirm: function (e) {
    const keyword = this.data.searchText
    wx.navigateTo({
      url: '../../goods/search/search?keyword=' + keyword + '&type=wait',
      fail: function (e) {
        console.log(e)
      }
    })
  },
  // 点击搜索关键词
  clickKeyWord: function (e) {
    console.log(e.currentTarget.dataset.id)
    const id = e.currentTarget.dataset.id
    const keywords = this.data.keywords
    let keyword = ''
    keywords.forEach(ele => {
      if (ele.id === id) {
        keyword = ele.keyword
      }
    })
    wx.navigateTo({
      url: '../../goods/search/search?keyword=' + keyword + '&type=atOnce'
    })
  },
  // 跳转到拼团页面
  toFightGroup: function () {
    wx.navigateTo({
      url: '../../fightGroup/fightGroup/fightGroup'
    })
  },
  // 跳转到商品详情页面
  toGoodsDetail: function (val) {
    wx.navigateTo({
      url: '../../goods/goodsDetail/goodsDetail?productId=' + val.currentTarget.id + '&storeId=' + this.data.storeId + '&type=normal'
    })
  },
  // 跳转到限时秒杀页面
  toSeckill: function () {
    wx.navigateTo({
      url: '../../activity/seckill/seckill'
    })
  },
  // 跳转到充值页面
  toRecharge: function () {
    wx.navigateTo({
      url: '../../myCard/recharge/recharge'
    })
  },
  // 跳转到领券中心页面
  toCouponCenter: function () {
    wx.navigateTo({
      url: '../../coupon/couponCenter/couponCenter'
    })
  },
  // 跳转到邀请好友页面
  toInvite: function () {
    wx.navigateTo({
      url: '../../invite/invite'
    })
  },
  // 积分商城页面跳转
  toScoreMall: function () {
    wx.navigateTo({
      url: '../../score/scoreMall/scoreMall'
    })
  },
  // 跳转到会员卡页面
  toMemberCard: function () {
    wx.navigateTo({
      url: '../../myCard/memberCard/memberCard'
    })
  },
  // 跳转到新用户专享
  toNewMbr: function () {
    wx.navigateTo({
      url: '../../activity/newmbrActivity/newmbrActivity'
    })
  },
  // banner跳转
  bannerJumping: function (e) {
    const that = this
    let bannerId = e.currentTarget.dataset.id
    const bannerList = that.data.banners
    let advertisementInfo = null
    bannerList.forEach(item => {
      if (item.id === bannerId) {
        advertisementInfo = item
      }
    });
    console.log(advertisementInfo)
    that.toAdPage(advertisementInfo, 'banner')
  },
  // 活动图（三分图）跳转
  activityJumping: function (e) {
    const that = this
    let bannerId = e.currentTarget.dataset.id
    const activityList = that.data.activityList
    let advertisementInfo = null
    activityList.forEach(item => {
      item.imageItems.forEach(ele => {
        if (ele.id === bannerId) {
          advertisementInfo = ele
        }
      })
    });
    console.log(advertisementInfo)
    that.toAdPage(advertisementInfo, 'activity')
  },
  // 前往广告页
  toAdPage: function (pageInfo, pageType) {
    const that = this
    if (pageInfo.linkType === 'APP') {
      // 应用
      // 判断跳转模块
      if (pageInfo.appReturnType === 'MIAOSHA') {
        wx.navigateTo({
          url: '../../activity/seckill/seckill'
        })
      } else if (pageInfo.appReturnType === "RECHARGE") {
        wx.navigateTo({
          url: '../../myCard/recharge/recharge'
        })
      } else if (pageInfo.appReturnType === "MEAL") {
        //  餐饮
      } else if (pageInfo.appReturnType === "RECEIVECOUPON") {
        // 领券中心
        wx.navigateTo({
          url: '../../coupon/couponCenter/couponCenter'
        })
      } else if (pageInfo.appReturnType === "ADVANCE_SELL_PRODUCT") {
        // 预售商品
        wx.navigateTo({
          url: '../../activity/advanceSell/advanceSell'
        })
      } else if (pageInfo.appReturnType === "TEAM_BUYING") {
        // 团购
        wx.navigateTo({
          url: '../../fightGroup/fightGroup/fightGroup'
        })
      } else if (pageInfo.appReturnType === "SCOREMALL") {
        // 积分商场
        wx.navigateTo({
          url: '../../score/scoreMall/scoreMall'
        })
      } else if (pageInfo.appReturnType === "INVITE_MEMBER") {
        // 邀请好友
        wx.navigateTo({
          url: '../../invite/invite'
        })
      } else if (pageInfo.appReturnType === "MEMBER_CARD") {
        // 会员卡
        wx.navigateTo({
          url: '../../myCard/memberCard/memberCard'
        })
      } else if (pageInfo.appReturnType === "MY_COUPON") {
        // 我的优惠券
        wx.navigateTo({
          url: '../../coupon/myCoupon/myCoupon'
        })
      } else if (pageInfo.appReturnType === "NEWMBR") {
        // 新用户专享
        wx.navigateTo({
          url: '../../activity/newmbrActivity/newmbrActivity'
        })
      } else if (pageInfo.appReturnType === 'GIFTCARD') {
        // 如果跳转类型是礼品卡，跳转到礼品卡界面
        wx.navigateTo({
          url: '../../../memberModule/giftCard/giftCard/giftCard'
        })
      }
    } else if (pageInfo.linkType === 'GRADPRODUCT') {
      // 秒杀商品
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=secondkill'
      })
    } else if (pageInfo.linkType === 'PRODUCT') {
      // 商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=normal'
      })
    } else if (pageInfo.linkType === 'TEAMPRODUCT') {
      // 拼团商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.teamActivityId + '&storeId=' + app.globalData.storeInfo.id + '&type=group'
      })
    } else if (pageInfo.linkType === "GIFTCARDACTIVITYDETAILS") {
      // 如果跳转类型是礼品卡详情，根据giftcardActivityId跳转到礼品卡详情页
      wx.navigateTo({
        url: '../../../memberModule/giftCard/giftCardBuy/giftCardBuy?giftCardActivityId=' + pageInfo.giftcardActivityId
      })
    } else if (pageInfo.linkType === 'COUPONACTIVITYDETAILS') {
      if (app.globalData.userInfo) {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../coupon/couponDetails/couponDetails?couponActivityId=' + pageInfo.couponActivityId + '&type=assign&isExternal=false'
          })
        } else {
          wx.showToast({
            title: '您还不是会员，请绑定手机号成为会员~',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            that.handlePopupPhone()
          }, 2000);
        }
      }
    } else if (pageInfo.linkType === 'URL') {
      // 链接
      let url = null
      if (pageType === 'activity') {
        url = pageInfo.linkUrl
      } else if (pageType === 'banner') {
        url = pageInfo.link
      }
      var index = '?'
      let webUrl = url
      if (url.indexOf(index) > -1) {
        webUrl = webUrl + '&storeId=' + this.data.storeId + '&type=normal'
      }
      let urlData = {
        url: encodeURIComponent(webUrl)
      }
      console.log(webUrl, urlData)
      let jsonUrl = JSON.stringify(urlData)
      wx.navigateTo({
        url: '../../advertising/advertising?webUrl=' + jsonUrl
      })
    } else {

    }
  },
  // 获取搜索关键字
  getSearchKeyword: function () {
    searchService.query().then(res => {
      console.log(res)
      if (res.length > 0) {
        let searchText = res[0].keyword
        let tempArray = []
        for (let i = 0; i < res.length; i++) {
          tempArray[i] = res[i];
        }
        let newKeyword = tempArray.shift()
        this.setData({
          searchText: searchText,
          keywords: tempArray
        })
      } else {
        this.setData({
          keywords: res
        })
      }
    })
  },
  // 类目点击事件
  clickCategory: function (e) {
    this.setData({
      tabSelected: e.currentTarget.dataset.idx
    })
  },
  // 点击切换门店
  changeStore: function () {
    wx.navigateTo({
      url: '../selectStore/selectStore'
    })
  },
  // 会员签到
  memberSignIn: function () {
    const that = this
    // this.setData({
    //   signModal: true
    // })
    memberService.signin().then(res => {
      wx.hideLoading()
      console.log(res)
      let tempData = {
        ...res,
        signed: false
      }
      that.setData({
        memberScore: tempData,
        signModal: true
      })
    }).catch(e => {
      console.log(e)
      if (app.globalData.userInfo.member) {
        let postData = {
          page: 1,
          pageSize: 0,
          memberIdEquals: app.globalData.userInfo.member.id
        }
        memberService.querySignin(postData).then(res => {
          wx.hideLoading()
          console.log(res)
          if (res.records && res.records.length > 0) {
            let now = new Date()
            let date = util.formatTime(now).replace(/\//g, '-')
            let time = date.split(' ');
            res.records.forEach(item => {
              let tempTime = item.signinTime.split(' ');
              if (tempTime[0] === time[0]) {
                let tempItem = {
                  ...item,
                  signed: true
                }
                that.setData({
                  memberScore: tempItem,
                  signModal: true
                })
              }
            })
          }
        })
      } else {
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  clickBlank: function (val) {
    if (val.currentTarget.dataset.type === 'signIn') {
      this.setData({
        signModal: false
      })
    }
  },
  clickBody: function () {

  },

  /**
   * 加入购物车 （老方法）
   * @param {*} val 
   */
  addShopcart: function (val) {
    console.log(val)
    var productId = val.currentTarget.dataset.id;
    let business = val.currentTarget.dataset.business;
    let storeId = ''
    let loginStatus = this.checkAuth()
    console.log(loginStatus)
    if (loginStatus) {
      if (business === "DISTRIBUTION") {
        try {
          var data = wx.getStorageSync('wj_distributionStore')
          if (data) {
            storeId = data.id
          }
        } catch (e) {}
      } else {
        storeId = app.globalData.storeInfo.id
      }
      var postData = {
        storeId: storeId,
        lists: [{
          count: 1,
          productId: productId
        }]
      }
      //storeId = app.globalData.storeInfo.id
      var balance = 0
      console.log(storeId, productId)
      productService.getDetails(storeId, productId).then(res => {
        console.log(res)
        if (res) {
          balance = res.balance
          if (balance === 0 || balance === null || balance === '') {
            wx.showToast({
              title: '门店中该商品库存不足，请选购其他商品~',
              icon: 'none',
              duration: 2000
            })
          } else {
            console.log(postData)
            shopcartService.cateringAdd(postData).then(res => {
              console.log(res)
              wx.showToast({
                title: '添加购物袋成功~',
                icon: 'none',
                duration: 2000
              })
            }).catch(err => {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            })
          }
        } else {
          wx.showToast({
            title: '添加购物袋失败~',
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '请先点击头像授权登录后添加哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 查询商品库存
   * @param {string} productId 
   */
  queryGoodsInventory: function (productId) {
    let storeId = app.globalData.storeInfo.id
    var balance = 0
    productService.getDetails(storeId, productId).then(res => {
      balance = res.balance
    })
    return balance
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/index/index/index?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/index/index/index',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },
  // 检查AccessToken是否过期
  // 通过接口测试AccessToken是否过期
  checkAccessToken: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      memberService.getMbrBalance().then(res => {
        console.log(res)
      }).catch(e => {
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    try {
      if (!app.globalData.userInfo) {
        return false;
      } else {
        return true;
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  // 记录会员访问门店
  recordVisitStore: function (storeId) {
    memberService.visitStore(storeId).then(res => {
      console.log(res)
    }).catch(e => {
      console.log(e.message)
    })
  },
  addShopcartTest: function (val) {

  },
  /**
   * 加入购物车 （新方法）
   * @param {object} val 
   */
  bindsubmit: function (val) {
    console.log(val.detail)
    const that = this
    var productId = val.detail.target.dataset.id;
    let business = val.detail.target.dataset.business;
    let balance = val.detail.target.dataset.balance;
    let storeId = ''
    let loginStatus = this.checkAuth()
    console.log(loginStatus)
    if (loginStatus) {
      if (business === "DISTRIBUTION") {
        try {
          var data = wx.getStorageSync('wj_distributionStore')
          if (data) {
            storeId = data.id
          }
        } catch (e) {}
      } else {
        storeId = app.globalData.storeInfo.id
      }
      var postData = {
        storeId: storeId,
        lists: [{
          count: 1,
          productId: productId
        }]
      }
      if (business === 'DISTRIBUTION') {
        balance = 0
        console.log(storeId, productId)
        productService.getDetails(storeId, productId).then(res => {
          console.log(res)
          balance = res.balance
          addShopcart(balance)
        })
      } else {
        addShopcart(balance)
      }
      /**
       * 加入购物车
       * @param balance 
       */
      function addShopcart(balance) {
        if (app.globalData.userInfo.member) {
          console.log(app.globalData.userInfo.member)
          if (balance === 0 || balance === null || balance === '') {
            wx.showToast({
              title: '门店中该商品库存不足，请选购其他商品~',
              icon: 'none',
              duration: 2000
            })
          } else {
            try {
              wx.setStorageSync('wj_wxa_formId', val.detail.formId)
            } catch (e) {}
            shopcartService.cateringAdd(postData).then(res => {
              console.log(res)
              wx.showToast({
                title: '添加购物袋成功~',
                icon: 'none',
                duration: 2000
              })
            }).catch(err => {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            })
          }
        } else {
          // wx.showToast({
          //   title: '请先绑定手机号码后再添加哦~',
          //   icon: 'none',
          //   duration: 2000
          // })
          that.handlePopupPhone()
        }
      }
    } else {
      wx.showToast({
        title: '请先点击头像授权登录后添加哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad(this.options)
    setTimeout(() => {
      // 特别处理iOS下有loading时下拉刷新秒回弹的问题
      wx.stopPullDownRefresh()
    }, 1000);
  },

  /**
   * 获取banner图片
   */
  getBannerList: function (storeId) {
    bannerService.getStoreBannerList('HOME', storeId).then(res => {
      console.log(res)
      this.setData({
        banners: res
      })
    })
  },
  getLoginDonateCouponAdsense: function (storeId) {
    bannerService.getStoreBannerList('LOGIN_DONATE_COUPON_ADSENSE', storeId).then(res => {
      console.log(res)
      if (res && res.length > 0) {
        this.setData({
          donateCoupons: res[0]
        })
      } else {
        this.setData({
          donateCoupons: {
            pictureUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/indexPopupCoupon.png',
            donateCouponActivityIds: '1058265468030156802,1058274165859041281,1058273873847402497'
          }
        })
        // 1058265468030156802,1058274440829222913,1058274165859041281,1058273873847402497
        let now = new Date()
        let time = (util.formatTime(now)).replace(/\//g, '-')
        let tempTimeArr = time.split(" ")
        let tempTermValidity = tempTimeArr[0] + ' 23:59:59'
        try {
          var value = wx.getStorageSync('wj_loginDonateCouponCount')
          if (value) {
            let tempTime = tempTermValidity.replace(/-/g, '/')
            let nowTime = new Date().getTime()
            let time = new Date(tempTime).getTime()
            if (nowTime > time) {
              this.toggleCouponPopup()
            }
            console.log(tempTime, time)
          } else {
            this.toggleCouponPopup()
          }
        } catch (error) {}
      }
    })
  },
  clickAssignCoupon: function () {
    const self = this
    let coupons = this.data.donateCoupons
    let now = new Date()
    let time = (util.formatTime(now)).replace(/\//g, '-')
    let tempTimeArr = time.split(" ")
    let tempTermValidity = tempTimeArr[0] + ' 23:59:59'
    let couponsArr = coupons.donateCouponActivityIds.split(',')
    console.log(couponsArr)
    for (let i = 0; i < couponsArr.length; i++) {
      const couponActivityId = couponsArr[i];
      let postData = {
        activityId: couponActivityId
      }
      couponService.assign(postData).then(res => {
        console.log(res)
        util.setHideLoading(true)
        let couponIds = []
        couponIds.push(res)
        if (self.data.show.coupon === true) {
          wx.showToast({
            title: "领券成功~",
            icon: 'none',
            duration: 2000
          })
          self.setData({
            'show.coupon': false
          });
          wx.setStorageSync('wj_loginDonateCouponCount', tempTermValidity)
        }
        return couponService.visited(couponIds)
      }).then(res => {
        console.log(res)
        if (i === couponsArr.length - 1) {
          util.setHideLoading(false)
        }
      }).catch(err => {
        util.setHideLoading(false)
        console.log(err)
        if (self.data.show.coupon === true) {
          if (err.code === 17010) {
            wx.showToast({
              title: "您今天已经领取过了~",
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          }
          self.setData({
            'show.coupon': false
          });
          wx.setStorageSync('wj_loginDonateCouponCount', tempTermValidity)
        }
      })
    }
  },
  recorderPopup: function () {
    this.toggleBottomPopup()
  },
  /**
   * 打开分享弹窗
   */
  toggleBottomPopup() {
    this.toggle('middle');
  },

  toggleCouponPopup: function () {
    this.toggle('coupon');
  },
  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type],
      [`overlayStyle`]: this.data.overlayStyle
    });
  },

  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
        self.getLoginDonateCouponAdsense(self.data.storeId)
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handleTabbar: function (e) {
    console.log(e.detail)
    if (e.detail.showTabbar === true) {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    } else {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  },
})